/* Copyright 2005 Sony Mathew, Minneapolis MN. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */package com.xsm.io;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author Sony Mathew
 *
 * Represents the result of reading a InputStream
 */
public class StreamResult {
    private int length = 0;
    private List streamSegments = new ArrayList(5);
    
    public void addSegment(byte[] segment) {
        streamSegments.add(segment);
    }
    
    /**
     * The Total length of the stream.
     */
    public int getLength() {
        return length;
    }

    /**
     * The Total length of the stream.
     */    
    public void setLength(int length) {
        this.length = length;
    }
    
    /**
     * List of segments read from from input stream.
     * The Segment sizes are expected to be exact.
     * 
     * @return List - of byte[]
     */
    public List getStreamSegments() {
        return streamSegments;
    }
    
    /**
     * List of segments read from from input stream.
     * The Segment sizes are expected to be exact.
     * 
     * @param List - of byte[]
     * 
     * author Sony Mathew
     */
    public void setStreamSegments(List streamSegments) {
        this.streamSegments = streamSegments;
    }
    
    /**
     * Get all the bytes as once.
     * author Sony Mathew
     */
    public byte[] getAllBytes() {
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream(getLength());
            write(bout);
            return bout.toByteArray();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
    
    /**
     * 
     * Write the segments to a OutputStream
     * @param OutputStream - out stream to write to
     * @throws IOException
     */
    public void write(OutputStream out) throws IOException {
		Iterator segmentIter = streamSegments.iterator();
		while (segmentIter.hasNext()) {
			byte[] segment = (byte[])segmentIter.next();
			out.write(segment, 0, segment.length);
		}
    }
}
